// 存储键名
const STORAGE_KEY = 'workRecords'

// 获取所有记录
export const getRecords = () => {
  return uni.getStorageSync(STORAGE_KEY) || []
}

// 保存记录
export const saveRecord = (record) => {
  const records = getRecords()
  const index = records.findIndex(r => r.id === record.id)
  
  if (index > -1) {
    records[index] = record
  } else {
    record.id = Date.now().toString()
    records.push(record)
  }
  
  uni.setStorageSync(STORAGE_KEY, records)
  return record
}

// 删除记录
export const deleteRecord = (id) => {
  const records = getRecords()
  const index = records.findIndex(r => r.id === id)
  
  if (index > -1) {
    records.splice(index, 1)
    uni.setStorageSync(STORAGE_KEY, records)
    return true
  }
  return false
}

// 获取月度统计
export const getMonthlyStats = (year, month) => {
  const records = getRecords()
  const monthRecords = records.filter(record => {
    const recordDate = new Date(record.date)
    return recordDate.getFullYear() === year && 
           recordDate.getMonth() + 1 === month
  })
  
  const totalHours = monthRecords.reduce((sum, record) => sum + record.hours, 0)
  const workDays = new Set(monthRecords.map(r => r.date)).size
  const hourlyRate = 30 // 每小时工资
  
  return {
    records: monthRecords,
    totalHours,
    workDays,
    totalAmount: (totalHours * hourlyRate).toFixed(2)
  }
}

// 导入Excel数据
export const importExcelData = (records) => {
  // 转换Excel数据格式
  const formattedRecords = records.map(record => ({
    id: Date.now().toString() + Math.random().toString(36).substr(2, 5),
    date: record.date,
    period: record.period || 'morning',
    hours: parseFloat(record.hours) || 0,
    content: record.content || ''
  }))
  
  // 保存到本地存储
  const existingRecords = getRecords()
  const newRecords = [...existingRecords, ...formattedRecords]
  uni.setStorageSync(STORAGE_KEY, newRecords)
  
  return formattedRecords
}

// 导出月度数据为CSV
export const exportMonthlyData = (year, month) => {
  const { records } = getMonthlyStats(year, month)
  let csvContent = '日期,时段,工时,工作内容\n'
  
  records.forEach(record => {
    const period = {
      morning: '上午',
      afternoon: '下午',
      overtime: '加班'
    }[record.period]
    
    csvContent += `${record.date},${period},${record.hours},${record.content}\n`
  })
  
  return csvContent
}